import {
  getCouponList,
  loginWithCode
} from "../../../api.js"
const COUPON_TYPE = {
  0: "unused",
  1: "used",
  2: "expired"
}

Page({
  data: {
    now: '?t=' + new Date().getTime(),
    couponList: {
      "unused": [],
      "used": [],
      "expired": []
    },
    currentKey: "unused",
    noUse: false, //默认不使用优惠券
    total: '',
  },
  onLoad: function (options) {
    if (options.total) {
      this.setData({
        total: options.total
      })
      // this.total = options.total
    }
    this.init()
  },

  init() {
    this.setCouponList()
  },
  // 设置代金券列表
  setCouponList() {
    let token = getApp().globalData.Store.token
    getCouponList(token).then(res => {
      if (res.data.code === 666) {
        this.tackleRep(res.data.data)
      } else if (res.data.code == 111111) {
        this.checkUserInfo()
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: "none"
        })
      }
    })
  },
  // 处理代金券数据 进行分类
  tackleRep(data) {
    let couponList = {
      "unused": data.use_list.data,
      "used": data.unuse_list.data,
      "expired": data.Expired_list.data
    }
    if (data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        if (Date.now() > new Date(data[i].expire_date).getTime()) {
          couponList.expired.push(data[i])
        } else {
          couponList[COUPON_TYPE[data[i].state]].push(data[i])
        }
      }
    }
    this.setData({
      couponList,
      currentList: couponList[this.data.currentKey]
    })
  },
  // 切换代金券列表
  handleCouponToggle(e) {
    let key = e.target.dataset.key
    this.setData({
      currentKey: key,
      currentList: this.data.couponList[key]
    })
  },
  // 代金券使用 缓存跳转回去进行读取 
  handleCouponUse(e) {
    this.setData({
      noUse: false
    })
    if (!this.data.total) {
      return wx.switchTab({
        url: '/pages/index/index',
      })
      getApp().endpage(new Date().getTime())
    };
    let id = e.currentTarget.dataset.id
    let currentCoupon = this.data.couponList["unused"].filter(a => a.id === id)[0]
    let startTime = new Date(currentCoupon.start_date).getTime();
    let now = new Date().getTime();
    let expireTime = new Date(currentCoupon.expire_date).getTime();
    if (now < startTime) {
      wx.showToast({
        title: `该优惠券还未到使用日期`,
        icon: "none"
      })
    } else if (now > expireTime) {
      wx.showToast({
        title: `该优惠券已过了有效日期`,
        icon: "none"
      })
    } else {
      wx.setStorageSync("coupon", currentCoupon)
      setTimeout(function () {
        wx.navigateBack()
      }, 1000)
    }
    //     else if(currentCoupon.total > this.data.total){
    //   wx.showToast({
    //     title: `您必须超过${currentCoupon.total}才能使用此券`,
    //     icon: "none"
    //   })
    // }
  },
  //选择是否使用优惠券
  useTicket() {
    this.setData({
      noUse: this.data.noUse ? false : true
    })
    wx.setStorageSync("coupon", '')
    setTimeout(function () {
      wx.navigateBack()
    }, 500)

  },
  // 检查用户信息授权
  checkUserInfo() {
    const xp = this;
    wx.getSetting({
      success: function (res) {
        if (!res.authSetting['scope.userInfo']) {
          xp.setData({
            isAuth: false
          })
          wx.navigateTo({
            url: '/pages/public/shouquan/shouquan',
          })
        } else {
          xp.setData({
            isAuth: true
          })
          wx.getUserInfo({
            success(res) {
              xp.loginWithCode(res.userInfo)
            }
          })
        }
      }
    })
  },
  //登陆
  loginWithCode(userInfo) {
    const xp = this
    wx.login({
      success({
        code
      }) {
        loginWithCode({
          ...userInfo,
          code,
          business_id: getApp().globalData.businessId
        }).then(res => {
          if (res.data.code === 666) {
            getApp().globalData.Store = res.data.data
            xp.init()
          }
        })
      }
    })
  },
  onShow() {
    getApp().startpage(new Date().getTime())
  },
  onHide() {
    getApp().endpage(new Date().getTime())
  },
})